<?php

namespace Liuhelong\LaravelAdmin\Wechat\Actions\WechatOffiaccountMenu;

use Encore\Admin\Actions\Action;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class Release extends Action
{
    public $name = '发布菜单栏';

    protected $selector = '.release';
	protected $menus;
	
	public function dialog()
    {
        $this->confirm('确定发布菜单栏？');
    }
	
    public function handle(Request $request)
    {
		$wechat = app('liuhelong_wechat_service');
		
		$this->menus = array_values(Arr::sort(cache('menus'), function ($value) {
			return $value['order'];
		}));
		$menus = [];
		$menus_level2 = [];
		$postions=[];
		foreach($this->menus as $menu){
			if($menu['parent_id']==0){
				$menus[] = $this->getMenu($menu);
				$postions[$menu['id']] = count($menus)-1;
			}else{
				
				$menus_level2[] = [
					'parent_id'=>  $menu['parent_id'],
					'content'=>$this->getMenu($menu)
				];
			}
		}
		
		foreach($menus_level2 as $menu_level2){
			if(empty($menus[$postions[$menu_level2['parent_id']]]['sub_button'])){
				
				$menus[$postions[$menu_level2['parent_id']]]['sub_button'] = [];
			}
			
			$menus[$postions[$menu_level2['parent_id']]]['sub_button'][] = $menu_level2['content'];
		}
		
		//dd($menus);
		$result = $wechat->handle('menu','create',[$menus]);
		
		return $this->response()->success('发布成功！')->refresh();
    }
	
	public function getMenu($menu){
		$array =[
			'name'=>$menu['name'],
		];
		$has_children = Arr::first($this->menus, function ($value, $key) use ($menu) {
			return $value['parent_id'] == $menu['id'];
		},false);

		if(!$has_children){
			
			$array['type'] = $menu['type'];
			switch($menu['type']){
				case('view'):
					$array['url'] = $menu['url'];
					break;
				case('click'):
					$array['key'] = $menu['key'];
					break;
				case('miniprogram'):				
					$array['appid'] = $menu['appid'];
					$array['pagepath'] = $menu['pagepath'];
					$array['url'] = $menu['url'];
					break;
				default:
				    $array['key'] = $menu['key'];
					break;
			}
		}
		return $array;
	}
	
    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-danger release"><i class="fa fa-arrow-up"></i> 发布菜单栏</a>
HTML;
    }
}